package com.sita.friend.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.GroupCreateRequest;
import com.sita.bike.rest.model.GroupCreateResponse;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.FormatUtils;
import com.sita.friend.Constant;
import com.sita.friend.FriendHelper;
import com.sita.tboard.ActivityBase;

import java.util.ArrayList;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by hongyun on 2016/2/2.
 */
public class FriendAddGroupAcitivity extends ActivityBase {


    private ListView listView;
    /**
     * 是否为一个新建的群组
     */
    protected boolean isCreatingNewGroup;
    /**
     * 是否为单选
     */
    private boolean isSignleChecked;
    private PickContactAdapter contactAdapter;
    /**
     * group中一开始就有的成员
     */
    private List<String> exitingMembers;

    private ImageView mBack;
    private Button mOK;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ////////////
        // 初始化 UI

        setContentView(R.layout.activity_group_pick_friend);

        mBack = (ImageView) findViewById(R.id.img_back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getParent().finish();
                finish();
            }
        });
        mOK = (Button) findViewById(R.id.friend_add_group_ok);
        mOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> groupmembers = getToBeAddMemberList();
                if(groupmembers.size()==0){
                    Toast.makeText(getApplicationContext(),"未选择好友",Toast.LENGTH_SHORT).show();
                }else if(groupmembers.size()==1){
                    Toast.makeText(getApplicationContext(),"人数不足，无法建组",Toast.LENGTH_SHORT).show();
                } else if(groupmembers.size()>=2) {
                    doCreateGroup();
                }

            }
        });

        // String groupName = getIntent().getStringExtra("groupName");
        String groupId = getIntent().getStringExtra("groupId");
        if (groupId == null) {// 创建群组
            isCreatingNewGroup = true;
        } else {
            // 获取此群组的成员列表
            EMGroup group = EMGroupManager.getInstance().getGroup(groupId);
            exitingMembers = group.getMembers();
        }
        if (exitingMembers == null)
            exitingMembers = new ArrayList<String>();
        // 获取好友列表
        final List<EaseUser2> alluserList = new ArrayList<EaseUser2>();
        for (EaseUser2 user : FriendHelper.getInstance().getContactList().values()) {
            if (!user.getUsername().equals(Constant.NEW_FRIENDS_USERNAME) &
                    !user.getUsername().equals(Constant.GROUP_USERNAME) &
                    !user.getUsername().equals(Constant.CHAT_ROOM) &
                    !user.getUsername().equals(Constant.CHAT_ROBOT))
                alluserList.add(user);
        }
        // 对list进行排序
//        Collections.sort(alluserList, new Comparator<EaseUser2>() {
//
//            @Override
//            public int compare(EaseUser2 lhs, EaseUser2 rhs) {
//                if(lhs.getInitialLetter().equals(rhs.getInitialLetter())){
//                    return lhs.getNick().compareTo(rhs.getNick());
//                }else{
//                    if("#".equals(lhs.getInitialLetter())){
//                        return 1;
//                    }else if("#".equals(rhs.getInitialLetter())){
//                        return -1;
//                    }
//                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
//                }
//
//            }
//        });

        listView = (ListView) findViewById(R.id.list);
        contactAdapter = new PickContactAdapter(this, R.layout.row_contact_with_checkbox, alluserList);
        listView.setAdapter(contactAdapter);
//        ((EaseSidebar) findViewById(R.id.sidebar)).setListView(listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
                checkBox.toggle();

            }
        });
    }


    private void doCreateGroup() {
        final GroupCreateRequest groupCreateRequest = new GroupCreateRequest();
        groupCreateRequest.mAccountId = AccountUtils.getAccountID();
        groupCreateRequest.mDescription = "Test code";
        groupCreateRequest.mMaxUsersNumber = 100;
//        groupCreateRequest.mIsPublic = false;
        groupCreateRequest.mIsPublic = true;
        groupCreateRequest.mName = "群组 @" + FormatUtils.formatShortCurrentTime();
        groupCreateRequest.mApproval = true;
        groupCreateRequest.mMemberIds = getToBeAddMembers();

        RestClient.getRestNormalService().newGroup(groupCreateRequest, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
                    // create successful
                    Log.d("Group", "create ok");
                    String s = RestClient.getGson().toJson(restResponse.mData);
                    GroupCreateResponse groupCreateResponse = RestClient.getGson().fromJson(s, GroupCreateResponse.class);

                    // create local group
                    doCreateLocalGroup(groupCreateResponse.mImGroupId,
                            groupCreateRequest.mDescription,
                            groupCreateRequest.mName,
                            getToBeAddMemberList());

                    // go to chat page
                    doGroupChat(groupCreateResponse.mImGroupId,groupCreateResponse.mGroupId);
                    // TODO: 2016/2/17 sava SITA 组id-环信组ID

                    return;
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("Group", "create ok");

            }
        });

    }

    private void doCreateLocalGroup(String groupId, String desc, String groupName, List<String> members) {
        try {
            String[] list = new String[members.size()];
            //EMGroupManager.getInstance().createPrivateGroup(groupName, desc, members.toArray(list), true, 200);
            EMGroupManager.getInstance().addUsersToGroup(groupId, list);
           // EMGroup group = EMGroupManager.getInstance().getGroupFromServer(groupId);
//            Log.d("sita group", group.getGroupName() + ": " + group.getMembers().size());
        }catch (final EaseMobException e) {
            Log.d("Group", "create new group");
        }

    }

    private void doGroupChat(String imGroupId,String locGroupId) {
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(Constant.CHAT_PARAMS_USER_ID, imGroupId);
        intent.putExtra(Constant.CHAT_PARAMS_LOC_GROUP_ID, locGroupId);
        intent.putExtra(Constant.CHAT_PARAMS_TYPE, Constant.CHATTYPE_GROUP);
        startActivity(intent);
        finish();
    }

    /**
     * 获取要被添加的成员
     *
     * @return
     */
//    private List<String> getToBeAddMembers() {
//        List<String> members = new ArrayList<String>();
//        int length = contactAdapter.isCheckedArray.length;
//        for (int i = 0; i < length; i++) {
//            String username = contactAdapter.getItem(i).getUsername();
//            if (contactAdapter.isCheckedArray[i] && !exitingMembers.contains(username)) {
//                members.add(username);
//            }
//        }
//
//        return members;
//    }

    //"287253620125073410,282787744755746399,272120661353170409"
    private String getToBeAddMembers() {
        String members = "";
        int length = contactAdapter.isCheckedArray.length;
        for (int i = 0; i < length; i++) {
            String userId = contactAdapter.getItem(i).getAccountId();
            if (contactAdapter.isCheckedArray[i] && !exitingMembers.contains(userId)) {
                String sep = (i == 0) ? "" : ",";
                members += sep + userId;
            }
        }

        return members;
    }

    private List<String> getToBeAddMemberList() {
        List<String> members = new ArrayList<String>();
        int length = contactAdapter.isCheckedArray.length;
        for (int i = 0; i < length; i++) {
            String accountId = contactAdapter.getItem(i).getAccountId();
            if (contactAdapter.isCheckedArray[i] && !exitingMembers.contains(accountId)) {
                members.add(accountId);
            }
        }
        return members;
    }

    /**
     * adapter
     */
    private class PickContactAdapter extends ArrayAdapter<EaseUser2> {

        private boolean[] isCheckedArray;
        List<String> list;
        List<EaseUser2> userList;
        List<EaseUser2> copyUserList;
        private LayoutInflater layoutInflater;
        private SparseIntArray positionOfSection;
        private SparseIntArray sectionOfPosition;
        private int res;


        public PickContactAdapter(Context context, int resource, List<EaseUser2> users) {
            super(context, resource, users);
            this.res = resource;
            this.userList = users;
            copyUserList = new ArrayList<EaseUser2>();
            copyUserList.addAll(users);
            layoutInflater = LayoutInflater.from(context);
            isCheckedArray = new boolean[users.size()];
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = getOwnView(position, convertView, parent);
//			if (position > 0) {
            final String username = getItem(position).getUsername();
            // 选择框checkbox
            final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
            ImageView avatarView = (ImageView) view.findViewById(R.id.avatar);
            TextView nameView = (TextView) view.findViewById(R.id.name);

            if (checkBox != null) {
                if (exitingMembers != null && exitingMembers.contains(username)) {
                    checkBox.setButtonDrawable(R.drawable.em_checkbox_bg_gray_selector);
                } else {
                    checkBox.setButtonDrawable(R.drawable.em_checkbox_bg_selector);
                }
                // checkBox.setOnCheckedChangeListener(null);

                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // 群组中原来的成员一直设为选中状态
                        if (exitingMembers.contains(username)) {
                            isChecked = true;
                            checkBox.setChecked(true);
                        }
                        isCheckedArray[position] = isChecked;
                        //如果是单选模式
                        if (isSignleChecked && isChecked) {
                            for (int i = 0; i < isCheckedArray.length; i++) {
                                if (i != position) {
                                    isCheckedArray[i] = false;
                                }
                            }
                            contactAdapter.notifyDataSetChanged();
                        }

                    }
                });
                // 群组中原来的成员一直设为选中状态
                if (exitingMembers.contains(username)) {
                    checkBox.setChecked(true);
                    isCheckedArray[position] = true;
                } else {
                    checkBox.setChecked(isCheckedArray[position]);
                }
            }
//			}
            return view;
        }

        private class ViewHolder {
            ImageView avatar;
            TextView nameView;
            TextView headerView;
        }

        private View getOwnView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                if (res == 0)
                    convertView = layoutInflater.inflate(R.layout.ease_row_contact, null);
                else
                    convertView = layoutInflater.inflate(res, null);
                holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
                holder.nameView = (TextView) convertView.findViewById(R.id.name);
                holder.headerView = (TextView) convertView.findViewById(R.id.header);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            EaseUser2 user = getItem(position);
            if (user == null)
                Log.d("ContactAdapter", position + "");
            String username = user.getUsername();
//            String header = user.getInitialLetter();
//
//            if (position == 0 || header != null && !header.equals(getItem(position - 1).getInitialLetter())) {
//                if (TextUtils.isEmpty(header)) {
//                    holder.headerView.setVisibility(View.GONE);
//                } else {
//                    holder.headerView.setVisibility(View.VISIBLE);
//                    holder.headerView.setText(header);
//                }
//            } else {
//                holder.headerView.setVisibility(View.GONE);
//            }


//            //设置头像
//            EaseUserUtils.setUserNick(username, holder.nameView);
//            //设置头像
//            EaseUserUtils.setUserAvatar(getContext(), username, holder.avatar);
//            String name = FriendHelper.getInstance().getContactUser(username)
            AccountUtils.setUserHeaderName(username, user.getAvatar(), holder.avatar, holder.nameView, getContext());

//
//            if(primaryColor != 0)
//                holder.nameView.setTextColor(primaryColor);
//            if(primarySize != 0)
//                holder.nameView.setTextSize(TypedValue.COMPLEX_UNIT_PX, primarySize);
//            if(initialLetterBg != null)
//                holder.headerView.setBackgroundDrawable(initialLetterBg);
//            if(initialLetterColor != 0)
//                holder.headerView.setTextColor(initialLetterColor);

            return convertView;
        }
    }
}
